/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package FrameWork;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

/**
 *
 * @author ThanhTri
 */
public class BestScore {
    private static BestScore instance = null;
    public int m_Score;
    public static BestScore get (){
         if( instance == null){
             instance =  new BestScore();
         }
         return instance;
    }
    private BestScore (){      
        m_Score = 0;
        loadData();
    }
    public void SaveScore() {
        try {
            RecordStore options = RecordStore.openRecordStore("data", true);
            byte[] data = saveOptions();

            if (options.getNumRecords() != 0){
                options.setRecord(1, data, 0, data.length);
            }else {
                options.addRecord(data, 0, data.length);
            }

            options.closeRecordStore();
        } catch (RecordStoreException ex) {
        }
    }
    public byte[] saveOptions() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        try {       
            dos.writeInt(m_Score);
            dos.flush();
        } catch (IOException ex) {
        }
        return baos.toByteArray();
    }
    public int loadData() {
        try {
            RecordStore options = RecordStore.openRecordStore("data", true);
            if (options.getNumRecords() != 0) {
                loadOptions(options.getRecord(1));
            }else{
                return 1;
            }
            options.closeRecordStore();
            
        } catch (RecordStoreException ex) {
        }
        return 1;
    }
    
    public void loadOptions(byte[] data) {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        DataInputStream dis = new DataInputStream(bais);
        
        try {        
        m_Score= dis.readInt();
        dis.close();
        } catch (IOException ex) {

        }
    }
}
